package com.zhangyu.shadow.ec.main.sort.content;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.log.ShadowLogger;
import com.zhangyu.shadow.ec.R;
import com.zhangyu.shadow.ec.R2;

import java.util.List;

import butterknife.BindView;

/**
 * @author zhangyu
 * @date 2017/11/7
 */

public class ContentDelegate extends RxShadowDelegate {

    private static final String ARG_CONTENT_ID = "CONTENT_ID";
    private int mContentId = -1;
    private List<SectionBean> mDataList;
    @BindView(R2.id.rv_list_content)
    RecyclerView mRecyclerView;

    public static ContentDelegate create(int contentId) {
        final ContentDelegate contentDelegate = new ContentDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(ARG_CONTENT_ID, contentId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle bundle = getArguments();
        if (bundle != null) {
            mContentId = bundle.getInt(ARG_CONTENT_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_list_content;
    }

    private void initData() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("sort_content_list.php?contentId=" + mContentId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        ShadowLogger.e("ContentDelegate", response);
                        mDataList = new SectionDataConverter().convert(response);
                        final SectionAdapter sectionAdapter = new
                                SectionAdapter(R.layout.item_section_content,
                                R.layout.item_section_header, mDataList);
                        mRecyclerView.setAdapter(sectionAdapter);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .get());
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initRecyclerView();
        initData();
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
    }
}
